package com.work.crops.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.work.crops.dao.CropsInfoIndexMapper;
import com.work.crops.dao.CropsInfoMapper;
import com.work.crops.pojo.CropsInfo;
import com.work.crops.pojo.CropsInfoIndex;
import com.work.crops.pojo.CropsParam;
import com.work.crops.service.CropsInfoService;
import com.work.entity.Result;
import com.work.entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CropsInfoServiceImpl implements CropsInfoService {

    @Autowired
    private CropsInfoMapper cropsInfoMapper;
    @Autowired
    private CropsInfoIndexMapper cropsInfoIndexMapper;

    @Override
    public List<CropsInfo> findAll() {
        return cropsInfoMapper.selectAll();
    }

    @Override
    public CropsInfo findById(Integer id) {
        return cropsInfoMapper.selectByPrimaryKey(id);
    }

//    条件分页查询
    @Override
    public PageInfo findByPage(Integer page, Integer size, CropsParam cropsParam) {
//        判断查询条件
        PageHelper.startPage(page, size);
        List<CropsInfo> list = cropsInfoMapper.findPage(cropsParam);
        return new PageInfo(list);
    }

//    添加农作物
    @Override
    public Result addCropsInfo(CropsInfo cropsInfo, CropsInfoIndex cropsInfoIndex[]) {
//        向数据库中添加一条数据
        Integer row = cropsInfoMapper.insertSelective(cropsInfo);

//        遍历数据指标数组
        for (CropsInfoIndex infoIndex : cropsInfoIndex) {
//            向中间表中循环添加数据
            infoIndex.setCid(cropsInfo.getId());
            cropsInfoIndexMapper.insert(infoIndex);
        }



        return new Result(row != null,
                row != null? StatusCode.ADD_OK:StatusCode.ADD_ERROR,
                row != null ? "添加成功" : "添加失败");
    }

//    删除农作物
    @Override
    public Result deleteById(String id) {
//        删除农作物信息之前判断设备是否监测到这个数据
        Integer count = cropsInfoMapper.findIndexIfBindDevice(id);
        if (count != 0){
            return new Result(false,StatusCode.DELETE_ERROR,"删除失败，农作物数据已与设备关联");
        }

//        删除农作物指标信息
         cropsInfoIndexMapper.findCropsInfoIndexByCid(id);

//         根据农作物id删除
        Integer row = cropsInfoMapper.deleteByExample(id);

        return new Result(row != null,
                row != null? StatusCode.ADD_OK:StatusCode.ADD_ERROR,
                row != null ? "删除成功" : "删除失败");
    }


//    修改农作物
    @Override
    public Result updateCropsInfoById(CropsInfo cropsInfo) {
        Integer row = cropsInfoMapper.updateByPrimaryKey(cropsInfo);

        return new Result(row != null,
                row != null? StatusCode.ADD_OK:StatusCode.ADD_ERROR,
                row != null ? "修改成功" : "修改失败");
    }


}

